package com.example.lemoncommon.util;

import com.example.lemoncommon.entity.UserTokenEntity;
import org.jose4j.jwe.*;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.consumer.InvalidJwtException;
import org.jose4j.keys.AesKey;
import org.jose4j.lang.JoseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.Key;

/**
 */
@SuppressWarnings("all")
public class UserTokenUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserTokenUtils.class);
    private static final byte[] key = {-6, 121, 109, -102, 111, 106, -66, -81, -10, -18, -11, -37, 23, -70, -49, -69};

    public static final ThreadLocal<UserTokenEntity> tokenHolder = new ThreadLocal<>();

    private static final String loginIdKey = "loginId";

    private static final String userNameKey = "userName";

    private static final String idKey = "id";

    private static final String createTimeKey = "createTime";

    private static final String userTypeKey = "userType";

    private static final String areaNoKey = "areaNo";

    /**
     * 获得KEY
     *
     * @return key
     */
    public static Key getKey() {
        return new AesKey(key);
    }

    /**
     * 获得密匙
     *
     * @return jwe
     */
    public static JsonWebEncryption getJWE() {
        JsonWebEncryption jwe = new JsonWebEncryption();
        jwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.A128KW);
        jwe.setEncryptionMethodHeaderParameter(ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256);
        jwe.setKey(getKey());
        return jwe;
    }

    public static String createToken(String id, String userName) {
        JsonWebEncryption jwe = getJWE();
        JwtClaims claims = new JwtClaims();
        claims.setClaim(idKey, id);
        claims.setClaim(userNameKey, userName);
        claims.setClaim(createTimeKey, System.currentTimeMillis());
        jwe.setPayload(claims.toJson());
        try {
            return jwe.getCompactSerialization();
        } catch (JoseException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 解析Token
     *
     * @param token token
     * @return token
     */
    public static UserTokenEntity parseToken(String token) throws JoseException, InvalidJwtException {
        UserTokenEntity entity = new UserTokenEntity();
        JsonWebEncryption jwe = new JsonWebEncryption();
        jwe.setKey(getKey());
        jwe.setCompactSerialization(token);
        JwtClaims claims = JwtClaims.parse(jwe.getPayload());
        entity.setId(claims.getClaimValue(idKey).toString());
        entity.setLoginId((String) claims.getClaimValue(loginIdKey));
        entity.setUserName((String) claims.getClaimValue(userNameKey));
        entity.setCreateTime(Long.parseLong(claims.getClaimValue(createTimeKey).toString()));
        tokenHolder.set(entity);

        return entity;
    }

    public static UserTokenEntity getTokenEntity() {
        return tokenHolder.get();
    }

    public static void main(String[] args) {
        try {
            System.out.println(UserTokenUtils.parseToken("eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.P00ltS94szKu5gwoBY65gP7lBuTw9Fu_LmQ_1Yu7k9GbSlTfWzWzZw.GjnBAqkn-HbTzlt03gNFtA.zlnhk_9qcz1mrIVAAmP8ddAc3kM3G4e63o9hqcLKwxVLa4D2vikcAgmoYCkC02ir2WpotqJf0xXrjO2hfPCrDTgX6Mnd91qCDmtHAzrMzNYvYP990EV0Q29rXZSiohjHMl87vY7tsxYt9z7IZzUlBAh2Xa9HMfjZJKc0skqLqfA.yYc2-q81bZynOCMgg8bllw").getId());
        } catch (JoseException e) {
            e.printStackTrace();
        } catch (InvalidJwtException e) {
            e.printStackTrace();
        }
    }

}
